"""百度 API 工具类"""
import json
import requests


class BaiduApi():
    """百度 API 客户端"""

    def __init__(self):
        self.API_KEY = "pUuuJK4QPnSL3JJHLVB1aRZ5"
        self.SECRET_KEY = "rv6oVtOXgjbNioRQSRJWk5dF9CbzZotV"

    def get_access_token(self):
        """
        使用 AK，SK 生成鉴权签名（Access Token）
        :return: access_token，或是None(如果错误)
        """
        url = "https://aip.baidubce.com/oauth/2.0/token"
        params = {
            "grant_type": "client_credentials",
            "client_id": self.API_KEY,
            "client_secret": self.SECRET_KEY
        }
        response = requests.post(url, params=params, timeout=10)
        return str(response.json().get("access_token"))

    def idcard(self, picurl):
        """身份证识别"""
        access_token = self.get_access_token()
        url = (
            "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard"
            f"?access_token={access_token}"
        )

        payload = (
            f'id_card_side=front&url={picurl}'
            '&detect_ps=false&detect_risk=false'
            '&detect_quality=false&detect_photo=false'
            '&detect_card=false&detect_direction=false'
        )
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Accept': 'application/json'
        }

        response = requests.request(
            "POST", url, headers=headers, data=payload, timeout=10
        )
        data = json.loads(response.text)
        print(data)

        # 检查是否有 error_code（百度 API 错误）
        if 'error_code' in data:
            return {
                "code": data['error_code'],
                "message": data.get('error_msg', '识别出错'),
                "raw_data": data  # 调试用
            }

        # 检查是否有识别结果
        if 'words_result' in data:
            try:
                words_result = data['words_result']
                # 百度身份证识别返回的是字典格式
                if isinstance(words_result, dict):
                    name = words_result.get('姓名', {}).get('words', '')
                    idcard_num = words_result.get(
                        '公民身份号码', {}
                    ).get('words', '')
                    return {
                        "code": 200,
                        "name": name,
                        'idcard': idcard_num,
                        "full_result": words_result
                    }
                # 如果是列表格式（旧版 API）
                elif isinstance(words_result, list) and len(
                    words_result
                ) >= 2:
                    name = words_result[0].get('words', '')
                    idcard_num = words_result[1].get('words', '')
                    return {
                        "code": 200,
                        "name": name,
                        'idcard': idcard_num
                    }
            except (KeyError, IndexError, TypeError) as e:
                return {
                    "code": 10011,
                    'message': f"解析结果失败: {str(e)}",
                    "raw_data": data
                }

        return {
            "code": 10010,
            'message': "识别出错或数据格式异常",
            "raw_data": data
        }

    def fontmessage(self, picurl):
        """文字识别"""
        access_token = self.get_access_token()
        url = (
            "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic"
            f"?access_token={access_token}"
        )

        payload = (
            f'url={picurl}&detect_direction=false'
            '&paragraph=false&probability=false'
        )
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Accept': 'application/json'
        }
        response = requests.request(
            "POST", url, headers=headers, data=payload, timeout=10
        )
        data = json.loads(response.text)
        name = data['words_result'][0]['words']
        code = data['words_result'][1]['words']
        return {"name": name, 'code': code}


bdapi = BaiduApi()